package ing.gzq.service;

import ing.gzq.base.Result;
import ing.gzq.base.ResultCache;
import ing.gzq.dao.FileDao;
import ing.gzq.model.SharedFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

import static ing.gzq.base.ResultCache.getDataOk;
import static ing.gzq.base.ResultCache.getFailureDetail;
import static ing.gzq.base.ResultCache.getPermissionDeniedDetail;
import static ing.gzq.service.AuthenticationService.getUserInSecurityContext;

@Service
public class FileService {

    public static String FILE_SAVE_DIR = "/root/file/mrcourse";

    @Autowired
    FileDao fileDao;

    @Autowired
    AuthenticationService authService;

    public Result uploadFile(Long courseId, MultipartFile file) {
        if(!authService.checkIfInCourse(courseId)){
            return getPermissionDeniedDetail("not in the course");
        }
        try {
            SharedFile sharedFile = new SharedFile();
            sharedFile.setId(UUID.randomUUID().toString().replace("-",""));
            sharedFile.setCourseId(courseId);
            sharedFile.setFileName(file.getOriginalFilename());
            sharedFile.setSize(file.getSize());
            sharedFile.setUploaderId(getUserInSecurityContext().getUsername());
            Path uri = Paths.get("mrcourse","download",courseId.toString(),sharedFile.getId(),sharedFile.getFileName());
            sharedFile.setPath(uri.toString());
            fileDao.insertFile(sharedFile);


            File fileDir = new File(FILE_SAVE_DIR);
            File savePath = new File(fileDir.getAbsolutePath() + File.separator+ courseId);
            if (!savePath.exists()) {
                savePath.mkdir();
            }
            file.transferTo(new File(savePath.getAbsolutePath() + File.separator + sharedFile.getId()));
            return ResultCache.OK;
        } catch (IOException e) {
            e.printStackTrace();
            return getFailureDetail(e.getMessage());
        }
    }

    public Result getFiles(Long courseId) {
        if(!authService.checkIfInCourse(courseId)){
            return getPermissionDeniedDetail("not in the course");
        }

        List<SharedFile> fileList = fileDao.getFileList(courseId);
        return getDataOk(fileList);
    }

}
